package com.wxapp.pay.service.util;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author lgl
 */
public class UrlUtil {
    private UrlUtil() {
    }

    public static String createLinkString(Map<String, String> params, boolean isDecode) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys); //按照参数key有序排列
        StringBuilder preset = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) { //有序合并参数
            String key = keys.get(i);
            String value = isDecode ? urlEncode(params.get(key)) : params.get(key);
            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                preset.append(key).append("=").append(value);
            } else {
                preset.append(key).append("=").append(value).append("&");
            }
        }
        return preset.toString();
    }

    /**
     * 字符串Url编码（大写）
     */
    public static String urlEncode(String temp) {
        return URLEncoder.encode(temp, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
    }
}
